﻿using System.Configuration;
using System.Data;
using RR;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected int dogdocCode;
    protected RegistRar regrar = new RegistRar();
    protected int placecount = 0;
    private int docdopID //код документа
    {
        get { return Convert.ToInt32(Request.QueryString["dcod"]); }
    }
    private int dogID //код документа
    {
        get { return Convert.ToInt32(Request.QueryString["ddog"]); }
    } 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["arcod"] != null)
            {
                int arcCode = Convert.ToInt32(Request.QueryString["arcod"]);
                OpenByArcPlace(arcCode);
                return;
            }

            if (Request.QueryString["dcod"] != null)
            {
                dogdocCode = Convert.ToInt32(Request.QueryString["dcod"]);

                Session["dogdocCode"] = dogdocCode; //код приложения
                Session["dogCode"] = Request.QueryString["ddog"]; //код договора

                SetLabel(Request.QueryString["dcod"]);
                GetDistinctArcPlace(Request.QueryString["dcod"]);
            }
            else
            {
                dogdocCode = -1;
                ReadOnly();
            }
        }
        if (rView.Report == null)
            rView.Report = GetReport();
    }

    private void GetDistinctArcPlace(string code)
    {
        lstArc.Items.Clear();
        int cod = Convert.ToInt32(code);
        var query = from d in regrar.DOGDOC
                    where d.DOGDOP.CODE == cod && d.ARCPLACE != null
                    select new { d.ARCPLACE1.CODE, d.ARCPLACE1.STRCODE };
        lstArc.TextField = "STRCODE";
        lstArc.ValueField = "CODE";
        lstArc.DataSource = query.Distinct().ToList();
        lstArc.DataBind();
    }

    private void SetLabel(string code)
    {
        int cod = Convert.ToInt32(code);
        var query = (regrar.DOGDOC.Where(d => d.DOGDOP.CODE == cod)).FirstOrDefault();
        if (query != null)
            lbl_page.Text = String.Format("Список документов к допсоглашению №{0} от {1}", query.DOGDOP.DOPNUM, query.DOGDOP.DOPDATE.ToShortDateString());
    }

    protected void OpenByArcPlace(int code)
    {
        ds_dogdoc.AutoGenerateWhereClause = false;
        ds_dogdoc.Where = "it.ARCPLACE = @code";
        ds_dogdoc.WhereParameters.Clear();
        ds_dogdoc.WhereParameters.Add("code", DbType.Int32, code.ToString());
        grd_doc.DataBind();
        //закрыть возможность редактирования
        ReadOnly();
    }

    private void ReadOnly(bool readOnly = true)
    {
        if (readOnly)
        {
            mMenu.Visible = false;
            btn_replace.Visible = false;
            flt_pop.Items.RemoveAt(1);
        }
    }

    protected void grd_doc_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("DOGDOC_gen");
        if (e.NewValues["DOPDOG"] == null)
            e.NewValues["DOPDOG"] = Convert.ToInt32(Request.QueryString["dcod"]);
    }
    protected void grd_doc_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        if (e.NewValues["DOPDOG"] == null)
            e.NewValues["DOPDOG"] = Convert.ToInt32(Request.QueryString["dcod"]);
    }
    protected void grd_DocType_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("DOCTYPE_gen");
    }

    protected void FillCombo(string Object, DevExpress.Web.ASPxEditors.ASPxComboBox cbb, EntityDataSource ds)
    {
        if (string.IsNullOrEmpty(Object)) return;

        ds.WhereParameters[0].DefaultValue = Object;
        cbb.DataBind();
    }

    protected void CreateItems(int cnt, DevExpress.Web.ASPxEditors.ASPxComboBox cbb)
    {
        cbb.Items.Clear();
        for (int i = 1; i <= cnt; i++)
        {
            cbb.Items.Add(i.ToString(), i);
        }
    }

    protected void clBack_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
        switch (e.Parameter)
        {
            case "distributeRec":
                DistributeRec(false);
                SetReportParams();
                //Response.Redirect(String.Format("/Arh/dogdoc.aspx?dcod={0}&ddog={1}", Session["dogdocCode"], Session["dogCode"]));
                //    GetArcplaceCode();
                break;
            case "distributeAllRec":
                DistributeRec(true);
                //SetReportParams();
                //Response.Redirect(String.Format("/Arh/dogdoc.aspx?dcod={0}&ddog={1}", Session["dogdocCode"], Session["dogCode"]));
                //    GetArcplaceCode();
                break;
            //case "GetArcCode":
            //    DistributeRec(false);
            //    Response.Redirect(String.Format("/Arh/dogdoc.aspx?dcod={0}&ddog={1}", Session["dogdocCode"], Session["dogCode"]));
            //    //    GetArcplaceCode();
            //    break;
            case "ClearAll":
                ClearArcPlace();
                SetReportParams();
                //    GetArcplaceCode();
                break;
            case "AddNewCompl":
                AddNewCompl();
                break;
            case "SaveDoc":
                SaveDoc();
                break;
            case "CreateMoveDoc":
                CreateMoveDoc();
                break;
            case "ReportParam":
                SetReportParams();
                break;
        }
    }

    private void SetReportParams()
    {
        //if (rView.Report == null)
        //    rView.Report = GetReport();
        DataSet ds = new DataSet();
        ds.Tables["DOGDOC_ARC"].Reset();
        //rView.Report.DataSource = ds;
        rView.Report.Parameters["DOPDOG"].Value = docdopID;
        
    }

    protected DogDocRep GetReport()
    {
        if ((DogDocRep)Session["report"] == null)
        {
            DogDocRep report = new DogDocRep();
            //report.DataSource = GetData();            
            Session["report"] = report;
        }

        return (DogDocRep)Session["report"];
    }

    private void CreateMoveDoc()
    {
        //создаем заголовок внутреннего перемещения
        int code = 0;
        bool isNotRec = true;
        string kontr = DOG.FindByKey(regrar, dogID).KONTRAGENT1.NAME;
        var query1 = (from d in regrar.DOGDOP
                      where d.CODE == docdopID
                      select d).First();
        DateTime dt = DateTime.Now;
        string note = string.Format("[авто]{0}, договор №{1}, доп. согл.№{2}", kontr, query1.DOG1.NOMDOG, query1.DOPNUM);
        regrar.MakeOrderDoc(docdopID, dt, Profile.UserInfo.ActiveWorker, Profile.UserInfo.ActiveWorker, note);        
    }

    private void SaveDoc()
    {
        DOGDOC doc = DOGDOC.CreateDOGDOC(regrar);
        doc.DATA = dt_DateDoc.Date;
        doc.NOMER = txt_DocNum.Text.Trim();
        doc.DOCTYPE = Convert.ToInt32(cbb_DocType.Value);
        doc.PAGENUM = Convert.ToInt32(spn_Kol.Value);
        doc.COMPLECTDOC = Convert.ToInt32(cbb_ComplDoc.Value);
        doc.DOPDOG = Convert.ToInt32(Request.QueryString["dcod"]);
        doc.NOTE = txt_Note.Text;

        regrar.SaveChanges();
    }

    private void AddNewCompl()
    {
        string name = btn_NewCompl.Text.Trim();
        //kontragent
        int code = Convert.ToInt32(Request.QueryString["dcod"]);
        if (code == 0)
            return;
        var query = (from d in regrar.DOGDOP
                     where d.CODE == code
                     select d).FirstOrDefault();
        if (query == null)
            return;
        int kontr = query.DOG1.KONTRAGENT;

        if (name != string.Empty)
        {
            COMPLECTDOC doc = COMPLECTDOC.CreateCOMPLECTDOC(regrar);
            doc.NAME = name;
            doc.KONTRAGENT = kontr;
            regrar.SaveChanges();
            btn_NewCompl.Text = string.Empty;
        }

        //throw new NotImplementedException(btn_NewCompl.Text);
    }

    private void ClearArcPlace()
    {
        int code = Convert.ToInt32(Request.QueryString["dcod"]);
        if (code == 0)
            return;
        regrar.CleadArcPlace(code);
        grd_doc.DataBind();
    }


    private ARCPLACE Arquery(int skipNum)
    {
        var query = from a in regrar.ARCPLACE
                    where a.STATE == 0
                    select a;
        int count = query.Count(); // 1st round-trip
        int index = new Random().Next(count);
        return (query.OrderBy(a => a.CODE).Skip(index).FirstOrDefault());
        return (from a in regrar.ARCPLACE
                where a.STATE == 0
                select a).OrderBy(a => a.CODE).Skip(skipNum).FirstOrDefault();
    }

    protected void DistributeRec(bool allPage)
    {
        int count = 0;
        int code = Convert.ToInt32(Session["dogdocCode"]);
        //int maxPage = Convert.ToInt16(spn_cnt.Number);
        int maxPage = 0;
        if (allPage)
        {
            maxPage = 10000;
        }
        else
        {
            maxPage = AppUtils.GetPageCount();
        }
        int mpage = maxPage;
        //int arcplace = Convert.ToInt32(cbb_object.Value);

        int arcplace = Arquery(count).CODE;
        var query = from q in regrar.DOGDOC
                    where q.DOPDOG == code && q.ARCPLACE == null
                    select q;

        foreach (var item in query)
        {
            if (mpage >= item.PAGENUM)
            {
                item.ARCPLACE = arcplace;
                mpage -= (int)item.PAGENUM;
            }
            else
            {
                count += 1;
                arcplace = Arquery(count).CODE;
                mpage = maxPage;
                if (mpage >= item.PAGENUM)
                {
                    item.ARCPLACE = arcplace;
                    mpage -= (int)item.PAGENUM;
                }
            }
        }
        //
        //Arquery.STATE = 2;  //установка статуса папке
        //
        regrar.SaveChanges();
        grd_doc.DataBind();

    }

    protected void btn_Exec_Click(object sender, EventArgs e)
    {
        //DistributeRec();
        Response.Redirect(String.Format("/Arh/dogdoc.aspx?dcod={0}&ddog={1}", Session["dogdocCode"], Session["dogCode"]));
    }

    protected void DeleteDir(string dir, bool recreate)
    {
        if (Directory.Exists(dir))
        {
            //удаляем все файлы в директории
            DirectoryInfo di = new DirectoryInfo(dir);
            foreach (FileInfo fi in di.GetFiles())
            {
                try
                {
                    fi.Delete();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        else
        {
            if (recreate)
                Directory.CreateDirectory(dir);
        }
    }
    protected void grd_doc_RowDeleted(object sender, DevExpress.Web.Data.ASPxDataDeletedEventArgs e)
    {
        string path = String.Format("/scans/{0}/", e.Values["CODE"]);
        if (path != "" && path != null)
            DeleteDir(Page.MapPath(path), false);
    }

    protected void grd_doc_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
    {
        //if (e.Column.FieldName == "ARCPLACE")
        //{
        //    var val = (string)e.GetListSourceFieldValue("ARCPLACE");
        //    if (val != null || val != "")
        //        e.Value = true;
        //    if (val == "" || val == null)
        //        e.Value = false;
        //}
    }
    protected void grd_doc_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e)
    {
        AppUtils.FocusInsertedRow(sender, e);
    }
    protected void cbb_ComplDoc_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        cbb_ComplDoc.DataBind();
    }
    protected void lstArc_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        GetDistinctArcPlace(Request.QueryString["dcod"]);
    }
    protected void rView_Load(object sender, EventArgs e)
    {
        rView.Report.Parameters["DOPDOG"].Value = docdopID;
    }
    protected void rView_Unload(object sender, EventArgs e)
    {
        rView.Report = null;
    }
}